// O(logn)
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {

        vector<int> leftSum(nums.size(), 0);
        vector<int> rightSum(nums.size(), 0);
        int sum = nums[0];

        for(int i = 1; i < nums.size(); ++i) {
            sum += nums[i];
            leftSum[i] = leftSum[i - 1] + nums[i - 1];
            rightSum[nums.size() - 1 - i] = rightSum[nums.size() - i] + nums[nums.size() - i];
        }

        int minSubArrayLength = INT_MAX;
        for(int i = 0; i < nums.size(); ++i){
            for(int j = nums.size() - 1; j >= i; --j){
                if(sum - leftSum[i] - rightSum[j] >= target){
                    minSubArrayLength = min(minSubArrayLength, j - i + 1);
                    // cout << j - i + 1 << "=" << sum - leftSum[i] - rightSum[j] << ' ' << i << "," << j << endl;
                } else {
                    break;
                }
            }
        }

        return minSubArrayLength == INT_MAX ? 0 : minSubArrayLength;
    }
};

// 滑动窗口 O(n)
class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int i = 0, sum = 0, result = INT_MAX;

        for (int j = 0; j < nums.size(); j++) {
            sum += nums[j];
            while(sum >= target){
                result = min(j - i + 1, result);
                sum = sum - nums[i];
                ++i;
            }
        }

        return result == INT_MAX ? 0 : result;
    }
};